/**
 * 该场景非固定长宽: ? x ?
 * 大小取决于列表的数据量
 * 
 * HTML 设置方案
 * #main
 *   #content
 *     -> 加载 pendants
 */

function createScene(context) {
  let t = new App(context);
  global.t = t;
  let scene = new context.Scene({
    require : [],
    init : (libs) => t.init(libs),
    destroy : () => t.destroy(),
    collectInfo : () => t.collectInfo(),
    onMessage : (key, data) => t.onMessage(key, data),
  });
  t.sendStatus = scene.sendStatus;
  return scene;
};


const pendantMap = {
  'planetaryExploration/moon' : 'flight/moon_record',
  'flightLog/cn/ver2021' : 'flight/flight_log',
  'flightLog/cn/ver2023' : 'flight/flight_launches',
};

class App {
  constructor(context) {
    this.context = context;

    // 要设置一个启动时就显示的挂件 (名)
    this.pendantName = 'flight/flight_launches';
    this.pendant = null;
  }

  // wait for overwrite
  sendStatus() {}

  init(libs) {
    initDom();
    this.handleInitParam();
    this.loadPendant();
  }

  destroy() {}

  collectInfo() {
    if (this.pendant == null) {
      return {};
    }
    return this.pendant.collectInfo();
  }

  onMessage(key, value) {
    switch (key) {
      case 'format': {
        if (typeof(value.format) == 'string') {
          this.params = value.params;
          let pendantName = pendantMap[value.format];
          pendantName != null && this.loadPendant(pendantName);
        }
        this.sendStatus();
      } return;
    }

    if (this.pendant == null || typeof(this.pendant.onMessage) != 'function') {
      console.log("universe_pictorial 收到命令: " + name, data);
      return;
    }
    this.pendant.onMessage(key, value);
  }

  handleInitParam() {
    const params = this.params = this.context.parseInitParam();
    if (params.format) {
      this.pendantName = pendantMap[params.format];
    }
  }

  loadPendant(name = this.pendantName) {
    if (name == null) {
      console.error('无法加载 Pendant: pendantName = null');
      return;
    }
    if (this.pendant != null) {
      this.context.destroyPendant(this.pendant);
      this.pendant = null;
    }
    this.pendantName = name;

    this.context.createPendant(name, {
      dom : elContent,
      params : this.params,
    }).then((pendant) => {
      this.pendant = pendant;
      this.pendant.sendStatus = () => this.sendStatus();
      this.pendant.sendStatus();
    });

    this.params = null;
  }
}

/** @type {HTMLElement} */ let elMain;
/** @type {HTMLElement} */ let elContent;

function initDom(width = 400, height = 400) {
  elMain = document.getElementById('main');

  elContent = document.createElement('div');
  elContent.id = 'content';
  elContent.style.position = 'absolute';
  elContent.style.overflow = 'hidden';
  elContent.style.left = '0px';
  elContent.style.top = '0px';
  elMain.appendChild(elContent);
  elContent.style.width = width + 'px';
  elContent.style.height = height + 'px';

  return [elMain, elContent];
}

export default createScene;
